package edu.yuhf.web.servlet;

import edu.yuhf.dao.mysql.UserJdbcDaoImpl;
import edu.yuhf.domain.User;
import edu.yuhf.service.UserServiceImpl;
import edu.yuhf.service.iface.UserService;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns= { "/init.servlet"})
public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserService userService=new UserServiceImpl();
		Cookie[] cookies=request.getCookies();
		boolean flag=false;
		String id="";
		/*
		Arrays.asList(cookies).stream().filter((cookie)->cookie.getName().equals("loginCookie")).forEach((element)->{
		});
		*/

		if(null!=cookies) {
			for(Cookie cookie:cookies) {
				if(cookie.getName().equals("loginCookie")) {
					id=cookie.getValue();
					flag=true;
					break;
				}
			}			
		}
		if(flag) {
			HttpSession session=request.getSession();
			Optional<User> optional=userService.getUser(Integer.valueOf(id));
			session.setAttribute("user",optional.orElse(null));
			//TODO :没有完成的功能
			session.setAttribute("name", optional.orElseGet(()->{
				System.out.println("null user");
				return new User();
			}).getUserName());
			request.getRequestDispatcher("views/main.jsp").forward(request, response);
		}else {
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
